package com.lxlg.lxlg_order.service.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeFastpayRefundQueryRequest;
import com.alipay.api.response.AlipayTradeFastpayRefundQueryResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lxlg.Lxlg_goods.client.GoodClient;
import com.lxlg.Lxlg_goods.client.param.MinusGoodNumberForm;
import com.lxlg.core.utils.Result;
import com.lxlg.lxlg_order.alipay.config.AlipayConfig;
import com.lxlg.lxlg_order.client.param.GoodsRefundForm;
import com.lxlg.lxlg_order.client.param.RefundMoneyForm;
import com.lxlg.lxlg_order.client.result.GoodsRefundInfo;
import com.lxlg.lxlg_order.common.OrderException.OrderException;
import com.lxlg.lxlg_order.common.OrderException.OrderExceptionCode;
import com.lxlg.lxlg_order.common.constvalue.AllOrderConstValue;
import com.lxlg.lxlg_order.common.util.TokenUtil;
import com.lxlg.lxlg_order.infra.mapper.GoodsOrderMapper;
import com.lxlg.lxlg_order.infra.mapper.GoodsRefundMapper;
import com.lxlg.lxlg_order.infra.mapper.OrderAndGoodsMapper;
import com.lxlg.lxlg_order.infra.mapper.SeckillOrderMapper;
import com.lxlg.lxlg_order.infra.model.GoodsOrder;
import com.lxlg.lxlg_order.infra.model.GoodsRefund;
import com.lxlg.lxlg_order.infra.model.OrderAndGoods;
import com.lxlg.lxlg_order.infra.model.SeckillOrder;
import com.lxlg.lxlg_order.service.service.GoodsRefundService;
import com.lxlg.lxlg_order.service.service.SeckillOrderService;
import com.lxlg.user_server.client.UserClient;
import com.lxlg.user_server.client.result.UserInfo;
import com.lxlg.user_server.client.result.UserLoginInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author kevin
 * @since 2022-04-28
 */
@Service
public class GoodsRefundServiceImpl extends ServiceImpl<GoodsRefundMapper, GoodsRefund> implements GoodsRefundService {
    @Resource
    private GoodsOrderMapper goodsOrderMapper;
    @Resource
    private SeckillOrderMapper seckillOrderMapper;
    @Resource
    private OrderAndGoodsMapper orderAndGoodsMapper;
    @Resource
    private UserClient userClient;
    @Resource
    private GoodClient goodClient;

    //生成退款订单
    @Override
    public Result<GoodsRefundInfo> doRequserReturn(GoodsRefundForm goodsRefundForm) {
        String userPhone = TokenUtil.getUserPhone();
        String userName = TokenUtil.getUserName();
        Integer userId = TokenUtil.getUserId();
        String refundCode= "t"+UUID.randomUUID().toString().replace("-","");
        Integer refundState=AllOrderConstValue.order_refundState_ready;
        String refundprice=null;
        Double refundScore=null;
        Integer orderType=null;
        Integer orderId=null;
        String orderCode=null;
        Integer skuId=null;
        Integer merchantId=null;
        Integer skuIdNum=null;

        //查询订单
        if (goodsRefundForm.getOrderType()== AllOrderConstValue.order_type_form) {
            //查询普通订单
            QueryWrapper<GoodsOrder> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("order_code",goodsRefundForm.getOrderCode());
            GoodsOrder goodsOrder = goodsOrderMapper.selectOne(queryWrapper);
            //
            QueryWrapper<OrderAndGoods> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("order_id",goodsOrder.getOrderId()).eq("sku_id",goodsRefundForm.getSkuId());
            OrderAndGoods orderAndGoods = orderAndGoodsMapper.selectOne(queryWrapper1);
            if (null==orderAndGoods) {
                throw new OrderException(OrderExceptionCode.NOTEXSIT_GOODS_ERROR);
            }
            //查看商品状态
            if (orderAndGoods.getGoodsState()== AllOrderConstValue.order_goodsState_orded||
                    orderAndGoods.getGoodsState()== AllOrderConstValue.order_goodsState_cancle||
                    orderAndGoods.getGoodsState()== AllOrderConstValue.order_goodsState_refund||
                    orderAndGoods.getGoodsState()== AllOrderConstValue.order_goodsState_returnalready) {
                throw new OrderException(OrderExceptionCode.GOOD_CANTREFUND_ERROR);
            }
            refundprice=orderAndGoods.getGoodsOrangePrice();
            refundScore=goodsOrder.getConsumeAllScore()*
                    new BigDecimal(orderAndGoods.getGoodsPayAllprice()).multiply(new BigDecimal(goodsOrder.getGoodsTotalPrice())).doubleValue();
            orderType=AllOrderConstValue.order_type_form;
            orderId=goodsOrder.getOrderId();
            orderCode=goodsOrder.getOrderCode();
            skuId=orderAndGoods.getSkuId();
            merchantId=orderAndGoods.getMerchantId();
            skuIdNum=orderAndGoods.getGoodsNum();

        }

        else {
            //查询秒杀订单
            QueryWrapper<SeckillOrder> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("seckill_order_code",goodsRefundForm.getOrderCode()).eq("sku_id",goodsRefundForm.getSkuId());
            SeckillOrder seckillOrder = seckillOrderMapper.selectOne(queryWrapper);
            if (null==seckillOrder) {
                throw new OrderException(OrderExceptionCode.NOTEXSIT_GOODS_ERROR);
            }
            if(seckillOrder.getSeckillOrderState()==AllOrderConstValue.order_payState_nopay||
                    seckillOrder.getSeckillOrderState()==AllOrderConstValue.order_payState_cancle||
                    seckillOrder.getSeckillOrderState()==AllOrderConstValue.order_payState_refund||
                    seckillOrder.getSeckillOrderState()==AllOrderConstValue.order_payState_returnalready){
                throw new OrderException(OrderExceptionCode.GOOD_CANTREFUND_ERROR);
            }
            //
            refundprice=seckillOrder.getGoodsPrice();
            refundScore=seckillOrder.getConsumeAllScore();
            orderType=AllOrderConstValue.order_type_seckill;
            orderId=seckillOrder.getSeckillOrderId();
            orderCode=seckillOrder.getSeckillOrderCode();
            skuId=seckillOrder.getSkuId();
            merchantId=seckillOrder.getSeckillMerchantId();
            skuIdNum=seckillOrder.getSeckillGoodsNums();

        }

        //生成退款订单
        GoodsRefund goodsRefund = new GoodsRefund();
        goodsRefund.setUserId(userId);
        goodsRefund.setUserName(userName);
        goodsRefund.setRefundCode(refundCode);
        goodsRefund.setRefundState(refundState);
        goodsRefund.setRefundPrice(refundprice);
        goodsRefund.setRefundScore(refundScore);
        goodsRefund.setOrderType(orderType);
        goodsRefund.setOrderId(orderId);
        goodsRefund.setOrderCode(orderCode);
        goodsRefund.setSkuId(skuId);
        goodsRefund.setManagerId(merchantId);
        goodsRefund.setSkuIdNum(skuIdNum);
        GoodsRefundInfo goodsRefundInfo = new GoodsRefundInfo();

        int insert = baseMapper.insert(goodsRefund);
        if(insert<1){
            throw new OrderException(OrderExceptionCode.REFUNDORDER_ADD_ERROR);
        }
        goodsRefundInfo.setRefundCode(goodsRefund.getRefundCode());
        return Result.getInstance(GoodsRefundInfo.class).setData(goodsRefundInfo);
    }
    //退款
    @Override
    public Result<?> doRefund(RefundMoneyForm refundMoneyForm) throws AlipayApiException {
        //查询退款订单
        QueryWrapper<GoodsRefund> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("refund_code",refundMoneyForm.getRefundCode());
        GoodsRefund goodsRefund = baseMapper.selectOne(queryWrapper);
        if(null==goodsRefund){
            throw new OrderException(OrderExceptionCode.NOTEXSIT_REFUNDORDER_ERROR);
        }
        //判断是否可以退款
        if (goodsRefund.getRefundState()!= AllOrderConstValue.order_refundState_ready) {
            throw new OrderException(OrderExceptionCode.REFUNDORDER_CANTREFUND_ERROR);
        }

        //退款
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        AlipayTradeFastpayRefundQueryRequest request = new AlipayTradeFastpayRefundQueryRequest();
        JSONObject bizContent = new JSONObject();
        Integer userId = TokenUtil.getUserId();
        /**
         * 获取用户的支付号
         */
        UserInfo user = userClient.inqueryUser().getData();

        bizContent.put("trade_no", user.getPayCode());
        bizContent.put("out_request_no",refundMoneyForm.getRefundCode());
        bizContent.put("refund_amount",goodsRefund.getRefundPrice());

        //// 返回参数选项，按需传入
        //JSONArray queryOptions = new JSONArray();
        //queryOptions.add("refund_detail_item_list");
        //bizContent.put("query_options", queryOptions);

        request.setBizContent(bizContent.toString());
        AlipayTradeFastpayRefundQueryResponse response = alipayClient.execute(request);
        if(response.isSuccess()){
            System.out.println("退款成功");
            //修改退款单状态
            goodsRefund.setRefundState(AllOrderConstValue.order_refundState_hasrefund);
            baseMapper.updateById(goodsRefund);
            //修改商品库存
            Integer skuId = goodsRefund.getSkuId();
            Integer skuIdNum = goodsRefund.getSkuIdNum();
            MinusGoodNumberForm minusGoodNumberForm = new MinusGoodNumberForm();
            minusGoodNumberForm.setSkuid(skuId);
            minusGoodNumberForm.setNum(skuIdNum);
            goodClient.minusGoodNumber(minusGoodNumberForm);

            //修改商品状态（修改订单装填）
            if(goodsRefund.getOrderType()==AllOrderConstValue.order_type_form){
                QueryWrapper<OrderAndGoods> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.eq("order_id",goodsRefund.getOrderId()).eq("sku_id",goodsRefund.getSkuId());
                OrderAndGoods orderAndGoods = orderAndGoodsMapper.selectOne(queryWrapper1);
                orderAndGoods.setGoodsState(AllOrderConstValue.order_goodsState_refund);
            }else {
                //秒杀订单状态
                QueryWrapper<SeckillOrder> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.eq("seckill_order_id",goodsRefund.getOrderId());
                SeckillOrder seckillOrder = seckillOrderMapper.selectOne(queryWrapper1);
                seckillOrder.setSeckillOrderState(AllOrderConstValue.order_payState_refund);
            }
            return Result.getInstance(String.class).setData("退款成功");

        } else {
            System.out.println("退款失败");
            return Result.getInstance(String.class).setData("退款失败");
        }




    }


}
